/*
 *通过mution间接更新state的多个方法的对象
 */
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORYS,
  RECEIVE_INFO,
  RECEIVE_SHOPS,
  RECEIVE_USER_INFO,
  RESET_USER_INFO,
  RECEIVE_GOODS,
  RECEIVE_RATINGS,
  UPDATE_FOOD_COUNT,
  CLEAR_SHOP_CART,
  RECEIVE_SEARCH_SHOPS
} from './mutation-types'
import {
  reqAddress,
  reqFoodCategorys,
  reqShops,
  reqUserinfo,
  reqLogout,
  reqShopGoods,
  reqShopInfo,
  reqShopRatings,
  reqSearchShops,
} from '../api'

export default {
  // 异步获取地址
  async getAddress ({commit, state}) {
    const geohash = state.latitude + ',' + state.longitude
    const result = await reqAddress(geohash)
    if (result.code === 0) {
      const address = result.data
      commit(RECEIVE_ADDRESS, {address})
    }
  },
  // 异步获取食品分类
  async getCategorys ({commit}) {
    const result = await reqFoodCategorys()
    if (result.code === 0) {
      const categorys = result.data
      commit(RECEIVE_CATEGORYS, {categorys})
    }
  },
  // 异步获取商家
  async getShops ({commit, state}) {
    const {longitude, latitude} = state
    const result = await reqShops(longitude, latitude)
    if (result.code === 0) {
      const shops = result.data
      commit(RECEIVE_SHOPS, {shops})
    }
  },
  // 同步存储用户信息
  saveUserInfo ({commit}, userInfo) {
    commit(RECEIVE_USER_INFO, {userInfo})
  },
  // 异步获取用户信息
  async getUserInfo ({commit}) {
    const res = await reqUserinfo()
    if (res.code === 0) {
      const userInfo = res.data
      commit(RECEIVE_USER_INFO, {userInfo})
    } else {
      const err = res.msg
      console.log('获取用户信息失败,', err)
    }
  },
  // 异步登出
  async logout ({commit}) {
    const res = await reqLogout()
    if (res.code === 0) {
      commit(RESET_USER_INFO)
    }
  },
  // 异步获取商家信息
  async reqShopInfo ({commit}) {
    const res = await reqShopInfo()
    if (res.code === 0) {
      const info = res.data
      commit(RECEIVE_INFO, {info})
    }
  },
  // 异步获取商家评价
  async reqShopRatings ({commit}, callback) {
    const res = await reqShopRatings()
    if (res.code === 0) {
      const data = res.data
      commit(RECEIVE_RATINGS, data)
      callback && callback()
    }
  },
  // 异步获取商家食物
  async reqShopGoods ({commit}, callback) {
    const res = await reqShopGoods()
    if (res.code === 0) {
      const data = res.data
      commit(RECEIVE_GOODS, data)
      callback && callback()
    }
  },
  updateFoodCount ({commit}, {isAdd, food}) {
    commit(UPDATE_FOOD_COUNT, {isAdd, food})
  },
  clearShopCart ({commit}) {
    commit(CLEAR_SHOP_CART)
  },
  async searchShops ({commit,state}, keyword) {
    const geohash = state.latitude + ',' + state.longitude
    const res = await reqSearchShops(geohash, keyword)
    if (res.code === 0) {
      const searchShops = res.data
      commit(RECEIVE_SEARCH_SHOPS, {searchShops})
    }
  },
  
}
